
const vscode = require("vscode");
const { exec } = require("child_process");
const fs = require('fs');
const path = require('path');

const { getChannel } = require('../outputChannel');

/**
 * @【命令处理程序】不跟踪此文件的更改
 */
function gitSkipFile(args) {
  const outputChannel = getChannel();

  // 获取右键菜单文件
  const filePath = args.resourceUri.fsPath;
  const workspaceRoot = vscode.workspace.workspaceFolders?.[0].uri.fsPath || "";

  console.log("[filePath]=====>", filePath);
  console.log("[workspaceRoot]=====>", workspaceRoot);

  // // 构造完整命令：切换目录 + 执行用户命令
  const gitCommand = `git -C "${workspaceRoot}" update-index --skip-worktree -- ${filePath}`;
  // 输出信息
  outputChannel.appendLine(`[gitCommand]=====>${gitCommand}`);

  // // 执行命令并处理结果
  exec(gitCommand, (error, stdout, stderr) => {
    if (error) {
      console.log("[error]=====>", error);
      outputChannel.appendLine(`[error]==>${error}`);
      return;
    }
    console.log("[sucess-stdout]=====>", stdout || "shell命令成功");
  });
}

/**
 * @【命令处理程序】打开 GitBash
 */
function openGitBash() {
  const outputChannel = getChannel();

  const workspaceRoot = vscode.workspace.workspaceFolders?.[0].uri.fsPath || "";

  // window系统  启动命令
  // const command = `start "Git Bash" "D:\\software\\Git\\git-bash.exe" -c "cd '${workspaceRoot}' && exec bash"`;
  // linux系统  启动命令

  const isWindows = process.platform === "win32";
  // let command = isWindows ? 'start cmd' : 'open -a Terminal';
  let command = "";
  if (isWindows) {
    command = `start cmd /k "cd /d \"${workspaceRoot}\"`;
  } else {
    // --working-directory 指定启动目录，-- 用于分隔参数
    command = `deepin-terminal -w ${workspaceRoot}`;
  }
  outputChannel.appendLine(`[open 命令]=====>${command}`);
  // 执行终端命令
  exec(command, (error) => {
    if (error) {
      console.error(`打开终端失败: ${error.message}`);
      return;
    }
  });
}
/**
 * @ 将文件添加 到 .git/info/exclude
 */
async function addToExclude(args) {
  const filePath = args.resourceUri.fsPath;
  const workspaceRoot = vscode.workspace.workspaceFolders?.[0].uri.fsPath || "";
  
  const relativePath = path.relative(workspaceRoot, filePath).replace(/\\/g, '/');
  // const excludeFile = path.join(workspaceRoot, '.git', 'info', 'exclude');
  
  const excludeFile = findGitDir(workspaceRoot)

  if(!excludeFile) return false

  // 读取并更新排除文件
  const content = fs.existsSync(excludeFile) 
    ? await fs.promises.readFile(excludeFile, 'utf8') 
    : '';

  if (!content.includes(relativePath)) {
    await fs.promises.appendFile(excludeFile, `${relativePath}\n`);
    vscode.window.showInformationMessage(`已添加 ${relativePath} 到 .git/info/exclude`);
  }
}

// 定位 git目录
function findGitDir(workspaceRoot) {
  let excludeFile = path.join(workspaceRoot, '.git', 'info', 'exclude');
  
  // 获取文件状态
  let isExist = fs.existsSync(excludeFile);
  if(isExist){
    return excludeFile
  }

  // 获取 workspaceRoot 的上一级目录
  const parentWorkspaceRoot = path.dirname(workspaceRoot);
  excludeFile = path.join(parentWorkspaceRoot, '.git', 'info', 'exclude');
  isExist = fs.existsSync(excludeFile);

  if(isExist){
    return excludeFile
  }

  vscode.window.showErrorMessage("没有找到.git目录");
}

module.exports = { gitSkipFile, openGitBash, addToExclude };
